<template>
    <div class="commit-box" v-loading="commitLoading">
        <div class="top-divider"></div>
        <div class="doc-info-box">
            <div class="create-by info-item">
                <img :src="docInfo.headImg ? docInfo.headImg : userImg">
                <span>{{ docInfo.createBy }}</span>
            </div>
            <div class="create-time info-item">
                <svg>
                    <use xlink:href="#keowledge-chuangjianshijian"></use>
                </svg>
                <span>{{ docInfo.createTime }}</span>
            </div>
            <div class="view info-item">
                <svg>
                    <use xlink:href="#keowledge-liulan"></use>
                </svg>
                <span>{{ viewNums }}</span>
            </div>
            <el-popover ref="editRecordsRef" :width="450" trigger="click" @show="editLog" placement="right-start"
                popper-class="edit-records-popper">
                <div class="edit-records-box" v-loading="editLoading">
                    <el-scrollbar ref="editlogRef" v-if="editLogList.length != 0">
                        <div class="edit-records-body">
                            <div class="edit-log-item" v-for="(item, index) in editLogList" :key="index">
                                <div class="user-name">
                                    <img :src="item.headImg || userImg">
                                    <span class="name">{{ item.userName }}</span>
                                </div>
                                <div class="oper">{{ item.operationType }}</div>
                                <div class="time">{{ item.createTime }}</div>
                            </div>
                        </div>
                    </el-scrollbar>
                    <jvs-empty v-if="editLogList.length == 0" size="250px"></jvs-empty>
                </div>
                <template #reference>
                    <div class="edit-records info-item">
                        <svg>
                            <use xlink:href="#keowledge-bianjijilu"></use>
                        </svg>
                        <span>{{ $t('message.text.editRecord') }}</span>
                    </div>
                </template>
            </el-popover>
        </div>
        <div class="start-box">
            <svg class="start-icon" @click="changeStart">
                <!-- keowledge-yidianzan -->
                <use v-bind:xlink:href="`#${isStart ? 'keowledge-yidianzan' : 'keowledge-weidianzan'}`"></use>
            </svg>
        </div>
        <div class="traver-line">
            <span>{{ isStart ? $t('message.text.haveLiked') : $t('message.text.justGiveLike') }}</span>
        </div>
        <div class="start-users-boxs">
            <div v-for="(item, index) in startList" :key="index" class="start-user-item">
                <el-tooltip :content="item.realName" effect="light">
                    <img :src="item.headImg ? item.headImg : userImg">
                </el-tooltip>
            </div>
        </div>
        <div class="commit-lists" v-if="commitList.length != 0">
            <div class="commit-title">{{ $t('message.text.allComments') }}</div>
            <div v-for="(item, index) in commitList" :key="index" class="commit-item">
                <div class="commit-top">
                    <div class="commit-info">
                        <img :src="item.headImg ? item.headImg : userImg">
                        <div class="commit-name">{{ item.name }}</div>
                        <div class="line"></div>
                        <div class="commit-time">{{ item.createTime }}</div>
                    </div>
                    <div class="commit-action">
                        <svg @click="cmmitLick(item, index)">
                            <use
                                v-bind:xlink:href="`${item.currentUserLike ? '#keowledge-dianzan-xuanzhong' : '#keowledge-dianzan-weixuanzhong'}`">
                            </use>
                        </svg>
                        <svg @click="deleteMsg(item, index)">
                            <use xlink:href="#keowledge-qingchulishijilu"></use>
                        </svg>
                    </div>
                </div>
                <!-- <el-scrollbar> -->
                <div class="commit-html" v-html="item.message"></div>
                <!-- </el-scrollbar> -->
            </div>
        </div>
        <div class="input-box" :class="[commitEdit && 'input-focus-box']">
            <div class="input-placeholder-box" @click="commitFocus" v-if="!commitEdit">
                {{ $t('message.text.pleaseEnterComment') }}
            </div>
            <div class="commit-engine-toolbar" :class="[commitEdit && 'show-toolbar']" v-resize="toolbarSize">
                <am-toolbar v-if="engine && commitEdit" :engine="engine" :items="items"></am-toolbar>
            </div>
            <div class="commit-input-box" v-if="commitEdit" :class="[commitEdit && 'commit-open']"
                :style="{ paddingTop: `${toolbarH + 4}px` }">
                <el-scrollbar>
                    <div id="inputEditor" ref="inputContainer" :style="{ height: `${440 - parseInt(toolbarH) - 4}px` }">
                    </div>
                </el-scrollbar>
            </div>
        </div>

        <div class="send-box" v-if="commitEdit">
            <el-button @click="closeCommit">{{ $t('message.buttons.cancal') }}</el-button>
            <el-button type="primary" @click="sendCommit">{{ $t('message.buttons.send') }}</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import userImg from "@/assets/common/user.png";
import Engine, {
    $,
    EngineInterface,
    isMobile,
    removeUnit,
} from "@aomao/engine";
import { ImageUploader } from "@aomao/plugin-image";
import AmToolbar from "@aomao/toolbar-vue";
import { cards, plugins, pluginConfig, onLoad } from "./config";
import { getLike, giveGood, leaveMsg, getDownViewNum, delMsg } from '@/api/common';
import { getCommentList, logPage } from '@/api/knowledge'
import useUserInfoStore from '@/store/userInfo';
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const userStore = useUserInfoStore()
const router = useRouter();
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const emit = defineEmits(["refreshScrollState"])
const props = defineProps({
    docInfo: {
        type: Object,
        default() {
            return {}
        }
    }
})
const commitList = ref([])
const commitEdit = ref(false)
const startList = ref([])
const isStart = ref(false)
// 编辑器容器
const inputContainer = ref<HTMLElement | null>(null)
// 编辑器引擎
const engine = ref<EngineInterface | null>(null);
const items = [
    [{
        type: "collapse",
        groups: [{
            items: [
                'image-uploader', "table",
            ]
        }]
    }],
    ["undo", "redo", "paintformat", "removeformat"],
    ["fontsize", "alignment"],
    ["bold", "italic", "strikethrough", "underline"],
    ["fontcolor", "backcolor"],
    ["link", "quote", "hr"],
]
const toolbarH = ref(36)
const commitLoading = ref(false)
const viewNums = ref(0)
onMounted(() => {
    init()
    getComment()
    getViewNum()
})
watch(() => props.docInfo, (newV, oldV) => {
    init()
    getComment()
    getViewNum()
}, {
    deep: true
})
function getViewNum() {
    if (userStore.userInfo?.id) {
        getDownViewNum(props.docInfo.id).then((res) => {
            if (res.data.code == 0) {
                viewNums.value = res.data.data?.SEE || 0;
            }
        });
    }
}
function toolbarSize({ height }) {
    toolbarH.value = height
}
function init() {
    commitLoading.value = true
    getLike({ bizType: "LIBRARY", bizResourceId: props.docInfo.id }).then(res => {
        if (res.data.code == 0) {
            startList.value = res.data.data
            isStart.value = false
            startList.value.forEach((item, index) => {
                if (item.userId == userStore.userInfo.id) {
                    isStart.value = true
                }
            })
            commitLoading.value = false
            emit('refreshScrollState')
        }
    }).catch(err => {
        commitLoading.value = false
    })
}
function getComment() {
    getCommentList(props.docInfo.id, { size: 20, currentPage: 1 }).then(res => {
        if (res.data.code == 0) {
            commitList.value = res.data.data.records
        }
    })
}
function commitFocus() {
    commitEdit.value = true
    nextTick(() => {
        if (inputContainer.value) {
            const engineInstance = new Engine(inputContainer.value, {
                placeholder: $t('message.text.pleaseEnterComment'),
                // 启用的插件
                plugins: plugins,
                // 启用的卡片
                cards: cards,
                // 所有的卡片配置
                config: {
                    ...pluginConfig,
                    [ImageUploader.pluginName]: {
                        file: {
                            action: `/mgr/jvs-auth/upload/jvs-public`,
                            headers: {
                                businessId: props.docInfo.id,
                                Authorization: 'Bearer ' + userStore.access_token
                            },
                            data: {
                                module: '/jvs-knowledge-ui/aomaoImage/'
                            },
                            limitSize: window.pluginConfig.editorUploadImgSize
                        },
                        parse: (response) => {
                            return {
                                data: response.data.fileLink,
                                result: response.code == 0
                            }
                        }
                    },
                },
            });
            onLoad(engineInstance);
            engineInstance.on("change", () => {
                // console.log("111")
            })
            engine.value = engineInstance;
            setTimeout(() => {
                inputContainer.value.focus()
            }, 100)
        }
    })
}
function closeCommit() {
    if (engine.value.getText()) {
        proxy.$confirm($t('message.confirm.contentNotSend'), $t('message.prompt'), {
            type: 'warning'
        }).then(res => {
            commitEdit.value = false
        })
    } else {
        commitEdit.value = false
    }

}
function changeStart() {
    giveGood({ bizType: "LIBRARY", bizResourceId: props.docInfo.id }).then(res => {
        if (res.data.code == 0) {
            proxy.$onePrompt.$oneNotify({
                title: $t('message.prompt'),
                message: `${isStart.value ? $t('message.message.startCancel') : $t('message.message.startFinish')}`,
                type: "success",
                position: "bottom-right"
            })
            isStart.value = !isStart.value
            changeStartList()
        }
    })
}
function changeStartList() {
    if (isStart.value) {
        startList.value.push({
            userId: userStore.userInfo.id,
            realName: userStore.userInfo.realName,
            headImg: userStore.userInfo.headImg
        })
    } else {
        let delIndex = -1
        startList.value.forEach((item, index) => {
            if (item.userId == userStore.userInfo.id) {
                delIndex = index
            }
        })
        if (delIndex != -1) {
            startList.value.splice(delIndex, 1)
        }
    }
}
const editLogList = ref<Object[]>([])
const editLoading = ref(false)
const editlogRef = ref()
function editLog() {
    editLogList.value = []
    // 登录才发送请求
    if (userStore.userInfo?.id) {
        editLoading.value = true
        logPage({ dcLibraryId: props.docInfo.id, size: 1000 }).then((res) => {
            if (res.data.code == 0) {
                editLogList.value = res.data.data.records || [];
            }
            nextTick(() => {
                editlogRef.value.update()
            })
            editLoading.value = false
        })
    }
}
function sendCommit() {
    if (engine.value.getText()) {
        leaveMsg({
            knowledgeId: props.docInfo.id,
            message: engine.value.getHtml(),
        }).then((res) => {
            if (res.data.code == 0) {
                getComment()
                commitEdit.value = false
            }
        });
    } else {
        proxy.$onePrompt.$oneNotify({
            message: $t('message.message.noComment'),
            title: $t('message.typeMenu.warning'),
            type: 'warning',
            position: 'bottom-right'
        })
    }
}
function cmmitLick(item, index) {
    giveGood({ bizType: 'COMMENT', bizResourceId: item.id }).then((res) => {
        if (res.data.code == 0) {
            commitList.value[index].currentUserLike = !commitList.value[index].currentUserLike
        }
    });
}
function deleteMsg(item, index) {
    proxy.$confirm($t('message.confirm.sureDeleteComment'), $t('message.prompt'), {
        confirmButtonText: $t('message.buttons.submit'),
        cancelButtonText: $t('message.buttons.cancal'),
        type: 'warning'
    }).then(() => {
        delMsg(item.id).then(res => {
            if (res.data.code == 0) {
                commitList.value.splice(index, 1)
            }
        })
    }).catch(e => { })
}
const editRecordsRef = ref()
function hiddenEditLog() {
    editRecordsRef.value.hide()
}
defineExpose({
    hiddenEditLog
})
</script>
<style lang="scss" scoped>
.commit-box {
    padding: 16px 8px 16px 24px;
    box-sizing: border-box;
    width: 100%;
    overflow-x: hidden;
    overflow-y: hidden;

    .top-divider {
        border-top: 1px solid #eeeff0;
        margin-bottom: 16px;
    }

    .doc-info-box {
        display: flex;
        align-items: center;

        .edit-records {
            cursor: pointer;
        }

        .info-item {
            display: flex;
            align-items: center;
            margin-right: 48px;

            svg {
                width: 14px;
                height: 14px;
                margin-right: 8px;
            }

            span {
                font-size: 14px;
                color: #6f7588;
            }
        }

        .info-item+.info-item {
            display: flex;
            align-items: center;
        }

        .create-by {
            img {
                width: 28px;
                height: 28px;
                border-radius: 6px 6px 6px 6px;
                overflow: hidden;
                margin-right: 8px;
            }
        }
    }

    .start-box {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 16px;
        margin-bottom: 16px;

        .start-icon {
            width: 48px;
            height: 48px;
            cursor: pointer;
        }
    }

    .traver-line {
        margin: 16px 0px !important;
        display: flex;
        justify-content: center;
        position: relative;
        font-size: 16px;

        &::before {
            content: '';
            height: 1px;
            width: 400px;
            background-color: #eeeff0;
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            top: 50%;
            z-index: 0;
        }

        span {
            color: #363b4c;
            z-index: 2;
            background-color: #FFFFFF;
            padding: 0px 16px;
        }
    }

    .start-users-boxs {
        display: flex;
        justify-content: center;
        margin-top: 26px;
        margin-bottom: 16px;
        flex-wrap: wrap;

        .start-user-item {
            min-width: 28px;
            width: 28px;
            height: 28px;
            border-radius: 6px 6px 6px 6px;
            border: 1px solid #FFFFFF;
            overflow: hidden;
            // box-sizing: border-box;
            position: relative;
            cursor: pointer;

            img {
                width: 100%;
                height: 100%;
            }
        }
    }

    .commit-lists {
        .commit-title {
            font-size: 16px;
            color: #494f6a;
            @include SourceHanSansCN-Bold;
            margin-bottom: 16px;
        }

        .commit-item {
            .commit-top {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .commit-info {
                    display: flex;
                    align-items: center;

                    img {
                        width: 28px;
                        height: 28px;
                        border-radius: 6px 6px 6px 6px;
                        overflow: hidden;
                        margin-right: 8px
                    }

                    .commit-name {
                        @include SourceHanSansCN-Bold;
                        font-size: 14px;
                        color: #363b4c;
                    }

                    .line {
                        width: 1px;
                        height: 14px;
                        background-color: #d78dbd;
                        margin: 0px 16px;
                    }

                    .commit-time {
                        font-size: 14px;
                        color: #6f7588;
                    }
                }

                .commit-action {
                    svg {
                        width: 16px;
                        height: 16px;
                        cursor: pointer;
                    }

                    svg+svg {
                        margin-left: 12px;
                    }
                }
            }

            .commit-html {
                padding: 12px 16px 0px 36px;
                font-size: 14px;
                color: #363b4c;

                #inputEditor {
                    height: auto !important;

                    ::v-deep(img) {
                        max-width: 100% !important;
                        height: auto !important;
                    }

                    ::v-deep(.editor-table-wrapper) {
                        &::-webkit-scrollbar {
                            cursor: pointer;
                            height: 6px;
                            opacity: 0;
                        }

                        /* 设置滚动条的背景色 */
                        &::-webkit-scrollbar-track {
                            background-color: transparent;
                        }

                        /* 设置滚动条的高度 */
                        &::-webkit-scrollbar-thumb {
                            border-radius: 5px;
                            background-color: transparent;
                            cursor: pointer;
                        }

                        /* 设置滚动条的鼠标悬停效果 */
                        &::-webkit-scrollbar-thumb:hover {
                            background-color: transparent;
                        }

                        &:hover {

                            /* 设置滚动条的高度 */
                            &::-webkit-scrollbar-thumb {
                                background-color: #aaaaaa;
                            }

                            /* 设置滚动条的鼠标悬停效果 */
                            &::-webkit-scrollbar-thumb:hover {
                                background-color: #888888;
                            }
                        }
                    }
                }
            }
        }

        .commit-item+.commit-item {
            margin-top: 16px;
        }
    }

    .input-box {
        height: 36px;
        min-height: 36px;
        background: #F5F6F7;
        border-radius: 4px 4px 4px 4px;
        margin-top: 18px;
        border: 1px solid #f5f6f7;
        position: relative;
        transition: all 0.2s;

        .commit-input-box {
            height: 0px;

            // transition: all 0.3s;
            #inputEditor {
                background-color: transparent;
                height: 400px;
                padding: 16px 16px 0px 16px;
                box-sizing: border-box;

                ::v-deep(.data-table) {
                    background-color: transparent !important;
                }
            }
        }

        .commit-engine-toolbar {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            min-height: 36px;
            z-index: 0px;
        }

        .show-toolbar {
            z-index: 2;
        }

        .commit-open {
            height: 450px;
            padding: 40px 0px 8px 0px;
            box-sizing: border-box;
        }

        .input-placeholder-box {
            cursor: pointer;
            height: 36px;
            line-height: 36px;
            font-size: 14px;
            color: #6f7588;
            padding: 0px 16px;
            box-sizing: border-box;
            z-index: 2;
            position: relative;
        }
    }

    .input-focus-box {
        height: 450px;
        border-color: #1E6FFF;
    }

    .send-box {
        text-align: right;
        margin-top: 12px;
    }
}
</style>
<style lang="scss">
.edit-records-popper {
    padding: 12px 0px !important;

    .edit-records-box {
        .edit-records-body {
            height: 320px;

            .edit-log-item {
                padding: 0px 12px;
                display: grid;
                grid-template-columns: 200px 75px 150px;

                .user-name {
                    display: flex;
                    align-items: center;

                    img {
                        width: 32px;
                        height: 32px;
                    }

                    .name {
                        margin-left: 8px;
                    }
                }

                .oper {
                    display: flex;
                    align-items: center;
                }

                .time {
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                }
            }

            .edit-log-item+.edit-log-item {
                margin-top: 8px;
            }
        }

    }
}
</style>